<?php
//require_once("./settings.php.inc");

function get_time_stamp()
{
	return date( 'Y-m-d H:i:s', time() );
}

function trimall($str, $charlist = " \t\n\r\0\x0B")
{
  return str_replace(str_split($charlist), '', $str);
}

function logit ($logStr, $level) {
	global $DBG_ENBLD;
	trigger_error($logStr,$level);
	//if ($DBG_ENBLD) print (get_time_stamp().$logStr."\n");
}

function log_error($logStr, $level, $file, $line){
	switch ($level){
		case E_USER_NOTICE:
			$logStr = 	"PHP Notice:  ".$logStr." in {$file} on line {$line}";
			break;
		case E_USER_WARNING:
			$logStr = 	"PHP Warning:  ".$logStr." in {$file} on line {$line}";
			break;
		default:
			$logStr = 	$logStr." in {$file} on line {$line}";
	}
	error_log($logStr);
}

function connect_to_mysql(){
	global $link;
	global $dbname, $dbuser, $dbpass;
	$link = mysql_connect('localhost', $dbuser, $dbpass); //opens or reuses the connection
	if (!$link) {
		return;
	}
	mysql_select_db ($dbname);
}


function print_mysql_status(){
	global $link;
	$status = explode('  ', mysql_stat($link));
	if (status != null){
		echo "\n========\nMYSQL STATUS\n=========\n";
		print_r($status);
		//echo "\n".mysql_stat($link)."\n";
	}
}

// generic database query wrapper 
// Use pecl/filter or mysql_real_string to avoid sql injection here
//function query_wrapper($query, $file, $line, $class, $function)
function query_wrapper($query, $file, $line, $function="main body")
{
	global $link;
	global $dbname, $dbuser, $dbpass;
	$link = mysql_connect('localhost', $dbuser, $dbpass); //opens or reuses the connection
	$mysql_status = mysql_stat($link);

	if( stripos($mysql_status,"MySQL server has gone away")!==FALSE || mysql_stat($link)==NULL ){ //This can happen if the mysql_server restarts...the link remains non null but invalid
		$link = mysql_connect('localhost', $dbuser, $dbpass, true); //forces a new connection(link) to be established
	}
	if (!$link) {
        	trigger_error("Database connection failed on {$file}:{$line} inside {$function}()",  E_USER_WARNING);
		return null;
	}
	mysql_select_db ($dbname);
	
    $r = mysql_query($query);
    if (!$r || $r===FALSE) {
      	trigger_error("Failed executing query '{$query}' on {$file}:{$line} inside {$function}()",  E_USER_WARNING);
       	return null;
    }
	return $r;
}
//$sql = "update curr_media_hotzone_status set is_in_media_hotzone='F', node_code='', media_cache_ip_port='', logtime=NOW()";
//print_r(query_wrapper($sql, __FILE__, __LINE__));
?>